<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>课程详情</title>
    <meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
    <link href="../../../css/mui.min.css" rel="stylesheet" />
    <link href="../css/common.css" rel="stylesheet" />
    <style>
      .video{
        padding: 1rem;
      }
      .video video{
        width: 100%;
        height: 14rem;
        background-color: #000000;
      }
      
      .poster{
        width: 100%;
        position: relative;
      }
      .poster img{
        width: 100%;
        position: absolute;
        height: 100%;
      }
      .mui-slider-group{
        height:calc(100vh - 345px);
      }
      .mui-control-content {
        background-color: white;
        min-height:calc(100vh - 345px);
        /* min-height: 100vh; */
      }
      .mui-control-content .mui-loading {
        margin-top: 50px;
      }
      .mui-segmented-control{
        display: table;
      }
      .mui-segmented-control .mui-control-item{
        display: table-cell;
      }
      .list{
        padding: 15px 10px;
        /* margin-top: 15px; */
      }
      .list +.list{
        border-top: 1px solid #dcdcdc;
      }
      .list p{
        margin-bottom: 2px;
      }
      .Img{
        width: 8rem;
        height: 5rem;
        border: 1px solid #dcdcdc;
        padding: 3px;
      }
      .Img img{
       width: 100%;
       height: 100%;
      }
      .icon{
        width: 1.5rem;
      }
      .icon img{
        width: 1.5rem;
        height: 1.5rem;
      }
      .textBg{
        padding: 10px;
        background: #FAFAFA;
        border: 1px solid #E3E3E3;
      }
      .mui-segmented-control.mui-segmented-control-inverted~.mui-slider-progress-bar{
        background: none;
        text-align: center;
      }
      .mui-segmented-control.mui-segmented-control-inverted~.mui-slider-progress-bar span{
        display: inline-block;
        width: 50%;
        height: 3px;
        left: 50%;
        transform: translate(-50%, -50%);
        -ms-transform:translate(-50%, -50%); 	/* IE 9 */
        -moz-transform:translate(-50%, -50%); 	/* Firefox */
        -webkit-transform:translate(-50%, -50%); /* Safari 和 Chrome */
        -o-transform:translate(-50%, -50%); 	/* Opera */
        background: url(../img/active.png) no-repeat center;
        background-size: 100% 100%;
        position: absolute;
        top: -3px;
      }
      .null{
        width: 1rem;
      }
      .poster img.default{
        width: 2.8rem;
        height: 2rem;
        position: absolute;
        left: 50%;
        top: 50%;
        transform: translate(-50%, -50%);
        -ms-transform:translate(-50%, -50%); 	/* IE 9 */
        -moz-transform:translate(-50%, -50%); 	/* Firefox */
        -webkit-transform:translate(-50%, -50%); /* Safari 和 Chrome */
        -o-transform:translate(-50%, -50%); 	/* Opera */
      }
	  .hide{display: none;}
    </style>
  </head>
  <body>
    <div class="container" id="container" v-cloak>
      <header class="mui-bar mui-bar-nav">
        <a class="mui-action-back mui-icon mui-icon-left-nav mui-pull-left"></a>
        <h1 class="mui-title">课程详情</h1>
      </header>
      <div id="" class="mui-content bg-white">
        <div id="" class="video">
          <!-- <div id="video" class="poster"style="height:14rem;background-color:#fff;" v-for="(item,index) in videoWareList" :key="index"  v-if="videoIndex==index"><img src="" alt=""v-if="!show">
          <video :id="'myVideo' + index" controls>
            <source :src="serverUrl + item.filePath"
              type="video/mp4"
            />
          </video>
          </div> -->
          <div id="video" class="poster"style="height:14rem;background-color:#F9F9F9;" ><img src="../img/default.png" alt=""v-if="videoWareList.length===0" class="default">
          
          </div>
        
        </div>
        
        <div id="slider" class="mui-slider">
          <div id="sliderSegmentedControl" class="mui-slider-indicator mui-segmented-control mui-segmented-control-inverted">
            <a class="mui-control-item mui-active" href="#item1mobile">
              视频
            </a>
            <a class="mui-control-item" href="#item2mobile">
              课件
            </a>
            <a class="mui-control-item" href="#item3mobile">
              基本信息
            </a>
          </div>
          <div id="sliderProgressBar" class="mui-slider-progress-bar mui-col-xs-4">
            <span></span>
          </div>
          <div class="mui-slider-group">
            <div id="item1mobile" class="mui-slider-item mui-control-content hide mui-active">
              <div id="scroll1" class="mui-scroll-wrapper">
                <div class="mui-scroll">
                  <div class="padding-lr">
                    <div class="list flex" v-for="(item,index) in videoWareList" :key="index" @click.stop="video(index)">
                      <div class="icon">
                        <img src="../img/video.png" >
                      </div>
                      <div class="text-cut padding-left" style="width:90%;display: flex;justify-content: space-between;" :class="videoIndex===index?'text-blue':''">
                        <div class="text-df text-cut">{{item.originalName}}</div>
						<!-- <div style="display: none;" :id="'ids'+index"> -->
						<div :style="{display:item.status?'block':'none'}" :id="'ids'+index">
							已完成
						</div>
                      </div>
                    </div>
                    <div class="padding text-center margin-top" v-if="courseWareList.length===0">
                      <img src="../img/null.png" alt="" class="null" style="width: 9rem;">
                      <p class="text-grey">
                        暂无数据
                      </p>
                    </div>
                  </div>
                  
                </div>
              </div>
            </div>
            <div id="item2mobile" class="mui-slider-item mui-control-content hide">
              <div id="scroll2" class="mui-scroll-wrapper">
                <div class="mui-scroll">
                  <div class="padding-lr">
                   <div class="list flex" v-for="(item,index) in courseWareList" :key="index" @click.stop="open(item)">
                     <div class="icon">
                       <img :src="item.originalName | fileType" >
                     </div>
                     <div class="text-cut padding-left">
                       <div class="text-df text-cut">{{item.originalName | ellipsis(20)}}</div>
                     </div>
                   </div>
                   <div class="padding text-center margin-top" v-if="courseWareList.length===0">
                     <img src="../img/null.png" alt="" class="null" style="width: 9rem;">
                     <p class="text-grey">
                       暂无数据
                     </p>
                   </div>
                  </div>
                  
                </div>
              </div>

            </div>
            <div id="item3mobile" class="mui-slider-item mui-control-content hide">
              <div id="scroll3" class="mui-scroll-wrapper">
                <div class="mui-scroll">
                  <div class="padding margin-lr">
                    <!-- <div class="padding-bottom-sm">讲师：<span class="text-blue">{{detail.name}}</span></div> -->
                    <div class="padding-bottom-sm">课程名称：<span class="text-blue">{{detail.name}}</span></div>
                    <div class="padding-bottom-sm">培训时间：<span class="text-blue">{{detail.createTime}}</span></div>
                    <!-- <div class="padding-bottom-sm">培训地点：<span class="text-blue">{{detail.name}}</span></div> -->
                    <div class="textBg">
                      {{detail.remarks}}
                    </div>
                  </div>
                </div>
              </div>

            </div>
          </div>
        </div>
      </div>
    </div>
    <script src="../../../js/mui.min.js"></script>
    <script type="text/javascript" src="../../../js/vue.js"></script>
    <script src="../../../js/jquery-1.7.2.min.js"></script>
    <script src="../js/mkeyplus.base.js"></script>
    <script src="../formal/js/api.js"></script>
    <script type="text/javascript">
		var flag = true;
      var courseDetail=null;
      var cv = null,id=null;
      var serverUrl=mui.baseWApp.serverUrl;//正式环境不需要此地址
      var user = JSON.parse(localStorage.getItem('outUser'));//当前用户信息
      var htapi = new HTGlobal();
      var videoPlayer=null;
      var video = null;
      var playing = false;
        mui.init();
        mui.plusReady(function() {
          cv = plus.webview.currentWebview();console.log(cv.form);
          id = cv.pageId?cv.pageId:'';
           plus.nativeUI.showWaiting('加载中');
           var videoTime = localStorage.getItem('videoTime')||'{}';//当前视频信息
           videoPlayer = JSON.parse(videoTime)
           console.log('获取缓存的信息'+JSON.stringify(videoPlayer))
          courseDetail.getData(id)
        })
      courseDetail = new Vue({
        el: '#container',
        data: {
          show:false,
          detail:{},
          videoWareList:[],//视频列表
          courseWareList:[],//课件列表
          videoIndex:0,//当前播放视频索引
          videoId:'',//当前播放的视频ID
          serverUrl:serverUrl,
		  token:'',
		  filePath:''
        },
        filters: {
          //根据不同的课件显示不同的图片
          fileType(filePath) {
            var index = filePath.lastIndexOf(".");
            var ext = filePath.substr(index + 1).toLowerCase();
            if (ext == "ppt" || ext == "pptx") {
              return '../img/ppt.png'
            }
            if (ext == "pdf") {
              return '../img/pdf.png'
            }
            if (ext == "png" || ext == "jpg") {
              return '../img/jpg.png'
            }
            if (ext == "doc" || ext == "docx") {
              return '../img/word.png'
            }
			if(ext == 'mp4' || ext =='mp3' ){
				return '../img/video.png'
			}
            return '../img/pdf.png'
          },
		  ellipsis (value,num) {
		        if (!value) return ''
		        if (value.length > num) {
		          return value.slice(0,num) + '...'
		        }
		        return value
		  }
        },
        methods:{
          getData(id){//获取详情
            var that = this;
            mui.baseWApp.httpRequst("/outsider/app/course/detail", {
				appUserId: user.id,
				id:id
            }, function(data) {
              console.log('课程详情+++++'+JSON.stringify(data.data))
              that.detail = data.data;
              var videoWareList = data.data.videoWareList;
              that.videoId = videoPlayer[id] ? videoPlayer[id].index : ''
              //处理视频数据
              if (videoWareList) {
                videoWareList.forEach(function(item, i) {
                  item.cwId = String(item.cwId);
                  // 上次观看时间
                  item.playTime = 0
                  if (that.videoId == item.cwId) {
                    that.videoIndex = i
                  }
                });
              }
              //缓存数据与当前视频数据做对比
              if (videoPlayer[id] && videoPlayer[id].time.length > 0) {
                videoWareList.forEach(function(item) {
                  videoPlayer[id].time.forEach(function(i) {
                    if (item.cwId == i.cwId) {
                      item.playTime = i.playTime
                    }
                  })
                })
              }
              that.videoWareList = videoWareList
              that.courseWareList = data.data.courseWareList;
               plus.nativeUI.closeWaiting();
               // video = new plus.video.VideoPlayer('video',{
               // 	// src:serverUrl + that.videoWareList[that.videoIndex].filePath,
               // 	src:'',
               //   poster:serverUrl + that.detail.coverImagePath
               // });
               plusReady()
            }, function() {
              plus.nativeUI.closeWaiting();
              console.log("获取数据失败");
            })
          },
          video(index){//视频切换
            this.videoIndex=index;
            video.close()
			// video.stop();
            plusReady();
          },
          //打开附件
          open: function(item) {
			  console.log('文档路径：'+courseDetail.filePath+item.cwId+'?token='+courseDetail.token)
			  
			var originalName = item.originalName
			var index = originalName.lastIndexOf(".");
			var ext = originalName.substr(index + 1).toLowerCase();
			//提交已观看课件
			previewEnd(10,item.cwId);
			
			if(ext=='pdf'){
				mui.openWindow({
					url:'../pdf/web/index.html',
					id:'../pdf/web/index.html',
					extras: {
						file:courseDetail.filePath+item.cwId+'?token='+courseDetail.token
					}
				})
				return;
			}
			  
			plus.nativeUI.showWaiting('文件读取中');
            var dtask = plus.downloader.createDownload(courseDetail.filePath+item.cwId+'?token='+courseDetail.token, {filename:"_downloads/" + item.originalName}, function(
              d, status) {
				plus.nativeUI.closeWaiting();
              if (status == 200) {
                var fileUrl = d.filename;
               plus.runtime.openFile(fileUrl, {}, function(e) {
                 alert('打开失败');
               });
              } else {
                alert("Download failed: " + status);
              }
            });
            dtask.start();
          }
        },
		created(){
			this.filePath = htapi.filePath;
			this.token = localStorage.getItem('token');
		}
      })
      mui.init({
        swipeBack: false
      });
      mui('.mui-scroll-wrapper').scroll({
          indicators: true //是否显示滚动条
        });
        
        
        // H5 plus事件处理
        function plusReady(){
			flag = true;
          var index=courseDetail.videoIndex;//当前播放索引
           var timeDisplay;//播放时间
		   
		   if(!courseDetail.videoWareList || courseDetail.videoWareList.length==0)
		   return;
		   
          // console.log('播放地址'+ courseDetail.filePath + courseDetail.videoWareList[index].cwId+'?token='+courseDetail.token)
        	// 创建视频播放控件
          //正式环境下不需要serverUrl
        	video = new plus.video.VideoPlayer('video',{
				src:courseDetail.videoWareList[index].filePath,
        		// src:courseDetail.filePath + courseDetail.videoWareList[index].cwId+'?token='+courseDetail.token,
            // src:'',
            poster:serverUrl + courseDetail.detail.coverImagePath,
			'show-play-btn':true,'enable-progress-gesture':false,'show-progress':false
			
        	}); 
          var playTime=courseDetail.videoWareList[index].playTime;
		  console.log('playTime='+playTime);
          if(playTime){
            video.seek(playTime);//播放起点位置
          }
          
          //监听播放
        	video.addEventListener('play', function(){
            courseDetail.videoId=courseDetail.videoWareList[index].cwId
        		updatePlaying(true);
        	}, false);
          //监听暂停
        	video.addEventListener('pause', function(){
        		updatePlaying(false);
        	}, false);
          //使用事件监听方式捕捉事件， 此事件可作为实时监测video 播放状态
          video.addEventListener("timeupdate",function(e){
			  document.querySelector('.mui-title').innerText = '课程详情'
            //用秒数来显示当前播放进度
            // console.log(JSON.stringify(e))
            timeDisplay = Math.floor(e.detail.currentTime);
            //记录观看时间
            courseDetail.videoWareList[index].playTime=timeDisplay;  
			if(Math.floor(e.detail.currentTime) == Math.floor(e.detail.duration)){
				// previewEnd(timeDisplay,courseDetail.videoId)
				courseDetail.videoWareList[index].playTime=0;//播放结束置0
				// courseDetail.videoWareList[index].played=true;
				// document.getElementById('ids'+index).style.display = 'block'
			}
			if(Math.floor(e.detail.currentTime) == Math.floor(e.detail.duration) && flag){
				console.log('播放完成。。。');
				flag = false;
				previewEnd(timeDisplay,courseDetail.videoId)
				// courseDetail.videoWareList[index].playTime=0;//播放结束置0
				courseDetail.videoWareList[index].played=true;
				document.getElementById('ids'+index).style.display = 'block'
			}
          },false);
          
          //监听播放结束
		  var that = this;
          video.addEventListener('ended', function(e){
			  
            console.log('播放结束' + JSON.stringify(e))
            previewEnd(timeDisplay,courseDetail.videoId)
            courseDetail.videoWareList[index].playTime=0;//播放结束置0
            courseDetail.videoWareList[index].played=true;
			document.getElementById('ids'+index).style.display = 'block'
			// mui.alert('视频播放完毕');
          }, false);
		  
		  video.addEventListener('waiting',function(e){
			  console.log('waiting.....',e);
		  })
		  
		  video.addEventListener('error',function(e){
		  			  console.log('error.....',e);
		  })
		  
		  //previewEnd(10,courseDetail.videoWareList[index].cwId);//自动设定视频观看完成
        }
        //预览结束请求后台
        function previewEnd(time,videoId){
          var data={
            wareId:videoId,
            userId:user.id,
            courseId:id,
            duration:time,
            status:1,
			enterpriseProjectId:user.enterpriseProjectId
          };
          htapi.fetch(data,function(data){
            if(data.code=='0'){
              console.log('记录成功'+JSON.stringify(data))
            }
            
          },false,'videoRecord','post')
        }
        
        // 更新为播放状态
        function updatePlaying(play) {
        	// playing = play;
          // if(play){
          //   video.seek(6)
          // }
        }
        var old_back = mui.back;  
        mui.back = function(){  
          //返回时存入视频的信息
            var videoTime = videoPlayer
            videoTime[id] = {
              index: courseDetail.videoId,
              time: courseDetail.videoWareList
            }
            videoTime = JSON.stringify(videoTime)
            localStorage.setItem("videoTime", videoTime);
            console.log('缓存视频成功')
          //继续当前页面原有返回逻辑  
		  mui.fire(plus.webview.currentWebview().opener(),'coursereload')
          old_back();  
        }	
        
    </script>
  </body>
</html>
